import 'dart:ui';

import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
import 'package:circular_check_box/circular_check_box.dart';
import '../public.dart';

/// 我的页面
class PursuePage extends StatefulWidget {
  PursuePage({Key key}) : super(key: key);

  @override
  _PursuePageState createState() {
    return _PursuePageState();
  }
}

class _PursuePageState extends State<PursuePage> {
  bool isEdit = false;
  UserRecordProvider userRecord;
  ThemeProvider theme;

  @override
  void initState() {
    super.initState();
    providerHanddle();
  }

  void providerHanddle() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      userRecord.setUserRecord();
    });
  }

  @override
  Widget build(BuildContext context) {
    // 使用Provider
    userRecord = Provider.of<UserRecordProvider>(context);
    theme = Provider.of<ThemeProvider>(context);
    int len = userRecord.userCollect?.length ?? 0;
    return Scaffold(
        backgroundColor: theme.primaryColor,
        appBar: AppBar(
          title: Text('追更'),
          leadingWidth: 44,
          leading: BackComponent(),
          backgroundColor: theme.primaryColor,
          centerTitle: true,
          actions: <Widget>[
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                if (len > 0) {
                  // setState(() {}); // 这里可以取消不用设置setState, 因为userRecord.checkedUserCollect存在更新操作
                  isEdit = !isEdit;
                  userRecord.checkedUserCollect([]);
                }
              },
              child: Container(
                padding: EdgeInsets.only(right: 16, left: 8),
                alignment: Alignment.center,
                child: Text('编辑'),
              ),
            )
          ],
        ),
        body: Column(children: [
          // 暂不实现
          // Container(
          //     height: 56,
          //     padding: EdgeInsets.only(left: 16),
          //     color: ColorUtil.rgba(40, 40, 56, 1),
          //     child: Row(
          //       mainAxisAlignment: MainAxisAlignment.spaceAround,
          //       children: [
          //         Row(
          //           children: [
          //             Text(
          //               '开启App推送，不错过漫画精彩更新',
          //               style: TextStyle(
          //                   fontSize: 14,
          //                   color: ColorUtil.rgba(255, 255, 255, 0.6)),
          //             ),
          //             SizedBox(
          //               width: 10,
          //             ),
          //             FlatButton(
          //                 shape: RoundedRectangleBorder(
          //                     side: BorderSide.none,
          //                     borderRadius:
          //                         BorderRadius.all(Radius.circular(14))),
          //                 padding: EdgeInsets.only(left: 12, right: 12),
          //                 color: ColorUtil.rgba(255, 255, 255, 0.05),
          //                 minWidth: 28,
          //                 height: 28,
          //                 child: Text(
          //                   '去打开',
          //                   style: TextStyle(
          //                       fontSize: 14,
          //                       color: ColorUtil.rgba(255, 255, 255, 0.6)),
          //                 ),
          //                 onPressed: () {
          //                   print('去打开');
          //                 })
          //           ],
          //         ),
          //         FlatButton(
          //             padding: EdgeInsets.all(0),
          //             minWidth: 20,
          //             height: 20,
          //             color: ColorUtil.rgba(255, 255, 255, 0.05),
          //             child: SVG.icon('close',
          //                 size: 10, color: ColorUtil.rgba(255, 255, 255, 0.2)),
          //             shape: RoundedRectangleBorder(
          //                 side: BorderSide.none,
          //                 borderRadius: BorderRadius.all(Radius.circular(10))),
          //             onPressed: () {
          //               print('close');
          //             })
          //       ],
          //     )),
          Expanded(
              child: len > 0
                  ? ListView.builder(itemCount: len, itemBuilder: _itemBuilder)
                  : EmptyComponent(
                      widgets: [
                        FlatButton(
                          onPressed: () {
                            Routers.navigateTo(RouterPage.READ_PAGE);
                          },
                          child: Text('去推荐看看'),
                          color: ColorUtil.rgba(255, 215, 59, 1),
                          height: 28,
                          minWidth: 48,
                          padding: EdgeInsets.only(left: 20, right: 20),
                          shape: RoundedRectangleBorder(
                              side: BorderSide.none,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(24))),
                        )
                      ],
                    )),
          isEdit
              ? Container(
                  color: ColorUtil.rgba(40, 40, 56, 1),
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        Expanded(
                            flex: 1,
                            child: FlatButton(
                              color: Colors.transparent,
                              // radius: BorderRadius.circular(0),
                              child: Text(
                                userRecord.isCheckedAllCollect ? '不选' : '全选',
                                style: TextStyle(
                                    color: Colors.white, fontSize: 16),
                              ),
                              onPressed: () {
                                userRecord
                                    .checkedUserCollect(userRecord.userCollect);
                              },
                            )),
                        SizedBox(
                          width: 1,
                          height: 16,
                          child: DecoratedBox(
                            decoration: BoxDecoration(
                                color: ColorUtil.rgba(18, 18, 26, 1)),
                          ),
                        ),
                        Expanded(
                            flex: 1,
                            child: FlatButton(
                              color: Colors.transparent,
                              child: Text(
                                '删除(${userRecord.checkedCollectNum})',
                                style: TextStyle(
                                    color: Colors.white, fontSize: 16),
                              ),
                              onPressed: () {
                                List<int> list = _getComicIds(true);
                                if (list.length > 0) {
                                  UserService.deleteUserCollect({
                                    'comic_id_list': list.join(','),
                                    'action': 'dels',
                                  }).then((res) {
                                    LogUtil.v(res, tag: 'deleteUserCollect');
                                    userRecord.deleteUserCollect(list);
                                    ACGN.toast.message('删除成功~');
                                  });
                                } else {
                                  ACGN.toast.message('没有可删除的数据~');
                                }
                              },
                            )),
                      ]),
                )
              : SizedBox.shrink()
        ]));
  }

  List<int> _getComicIds([isChecked = false]) {
    List<int> list = [];
    userRecord.userCollect.forEach((item) {
      if (isChecked && item.isChecked) {
        list.add(item.comicId);
      } else {
        list.add(item.comicId);
      }
    });
    return list;
  }

  Widget _itemBuilder(context, index) {
    UserCollectItemModel item = userRecord.userCollect[index];
    return Container(
        height: 124,
        padding: EdgeInsets.only(
            left: isEdit ? 8 : 16, right: 16, top: 12, bottom: 12),
        child: Row(children: [
          isEdit
              ? SizedBox(
                  width: 36,
                  height: 32,
                  child: FittedBox(
                      alignment: Alignment.centerLeft,
                      child: CircularCheckBox(
                          value: item.isChecked,
                          inactiveColor: ColorUtil.rgba(77, 77, 108),
                          activeColor: ColorUtil.rgba(254, 45, 102),
                          materialTapTargetSize:
                              MaterialTapTargetSize.shrinkWrap,
                          onChanged: (bool val) {
                            userRecord.checkedUserCollect([item]);
                          })))
              : SizedBox.shrink(),
          Expanded(
              child: Container(
                  margin: EdgeInsets.only(right: 10),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      Container(
                          width: 75,
                          margin: EdgeInsets.only(right: 10),
                          child: ClipRRect(
                            borderRadius: BorderRadius.all(Radius.circular(8)),
                            child: Stack(children: [
                              AspectRatio(
                                  aspectRatio: 0.75,
                                  child: ImagesNetworkComponent(item.cover3x4)),
                              getIconNew(item.updateTime > item.readTime)
                            ]),
                          )),
                      Expanded(
                          child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                              children: [
                            Text(
                              item?.comicName,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style:
                                  TextStyle(fontSize: 16, color: Colors.white),
                            ),
                            Text(
                              '${item.lastChapterName}',
                              overflow: TextOverflow.ellipsis,
                              maxLines: 1,
                              style: TextStyle(
                                  fontSize: 14,
                                  color: ColorUtil.rgba(255, 255, 255, 0.6)),
                            )
                          ]))
                    ],
                  ))),
          !isEdit
              ? FlatButton(
                  padding:
                      EdgeInsets.only(top: 5, bottom: 5, left: 12, right: 12),
                  height: 28,
                  minWidth: 0,
                  color: ColorUtil.rgba(255, 215, 59, 1),
                  shape: RoundedRectangleBorder(
                      side: BorderSide.none,
                      borderRadius: BorderRadius.all(Radius.circular(14))),
                  onPressed: () {
                    Routers.navigateTo(RouterPage.READ_PAGE, params: {
                      'comicId': item.comicId,
                      'chapterId': 0,
                      'comicIds': _getComicIds()
                    });
                  },
                  child: Text(
                    '免费看',
                    style: TextStyle(
                        fontSize: 14, color: ColorUtil.rgba(51, 51, 51, 1)),
                  ))
              : SizedBox.shrink()
        ]));
  }
}
